package com.xique.blelock.view.Setting;

import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.clj.fastble.BleManager;
import com.clj.fastble.data.BleDevice;
import com.ivin.crop.Log;
import com.ivin.refreshlayout.QRefreshLayout;
import com.ivin.refreshlayout.RefreshHandler;
import com.xique.blelock.Adapter.DeviceMessageAdapter;
import com.xique.blelock.Adapter.RecordAdapter;
import com.xique.blelock.NetUtils.NetResult;
import com.xique.blelock.NetUtils.XqNetClient;
import com.xique.blelock.R;
import com.xique.blelock.Utils.Stringkey;
import com.xique.blelock.Utils.TimeUtil;
import com.xique.blelock.model.HistoryMessageInfo;
import com.xique.blelock.model.MessageType;
import com.xique.blelock.model.UnreadMessage;
import com.xique.blelock.view.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class devicemessages extends BaseActivity implements View.OnClickListener {


    @BindView(R.id.title)
    TextView title;

    @BindView(R.id.rightbutton)
    TextView rightbutton;

    @BindView(R.id.RecyclerView)
    RecyclerView recyclerView;

    @BindView(R.id.nomessage)
    View nonemessage;

    @BindView(R.id.refreshLayout)
    QRefreshLayout refreshLayout;

    private DeviceMessageAdapter deviceMessageAdapter;

    private List<HistoryMessageInfo> historyMessageInfoList = new ArrayList<>();

    // 判断是不是点击通知跳转过来的
//    private boolean isJpushMessage = false;
    private  BroadcastReceiver mReceiver;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.devicemessages);
        ButterKnife.bind(this);
        initview();

        getSystemHistory();

        IntentFilter filter = new IntentFilter();
        filter.addAction(Stringkey.Device_Message_Event);
        mReceiver = new DeviceMessagePush();
        this.registerReceiver(mReceiver, filter);
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        super.onDestroy();

    }

    private void getSystemHistory() {
        //getUnreadMessageCount
        XqNetClient netClient =  new XqNetClient();
        JSONObject jsonobject = new JSONObject();

        String time = null;
        if(historyMessageInfoList.size()>0){
            time = historyMessageInfoList.get(historyMessageInfoList.size()-1).getTimestamp();
        }

        try {
            jsonobject.put(Stringkey.Token, userInfo.getToken());
            jsonobject.put(Stringkey.UID, userInfo.getUid());
            jsonobject.put(Stringkey.Timestamp, TimeUtil.getSystemCurrentTimeLong()+"");
            jsonobject.put(Stringkey.ToTal, 10);
            jsonobject.put(Stringkey.Time, (time==null)?TimeUtil.getSystemCurrentTimeLong():time);
            jsonobject.put(Stringkey.Type, MessageType.device+"");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        showProgressDialog();
        netClient.getHistoryMessages(jsonobject.toString()).enqueue(new Callback<NetResult<List<HistoryMessageInfo>>>(){//获取验证码
            @Override
            public void onResponse(Call<NetResult<List<HistoryMessageInfo>>> call, Response<NetResult<List<HistoryMessageInfo>>> response) {
                Log.e("获取到的消息是："+ com.alibaba.fastjson.JSONObject.toJSONString(response), "");
                if(response.body().isSuccess()){
                    List<HistoryMessageInfo> templist = response.body().getData();
                    Log.e("获取到的消息是："+ com.alibaba.fastjson.JSONObject.toJSONString(templist), "");
                    refreshLayout.loadMoreComplete();
                    if(templist.size() > 0) {
                        historyMessageInfoList.addAll(templist);
                        Collections.sort(historyMessageInfoList);
                        refreshLayout.setVisibility(View.VISIBLE);
                        nonemessage.setVisibility(View.GONE);
                        deviceMessageAdapter.setDeviceList(historyMessageInfoList);
                        deviceMessageAdapter.notifyDataSetChanged();

                        //遍历把查询下来的都设置为已经度过
                        setMessageIsRead();
                    }
                    if(historyMessageInfoList.size() == 0){
                        refreshLayout.setVisibility(View.GONE);
                        nonemessage.setVisibility(View.VISIBLE);
                    }


                }else {
                    showToast(devicemessages.this, "没有获取到设备列表 ");
                }
                hideProgressDialog();
            }

            @Override
            public void onFailure(Call<NetResult<List<HistoryMessageInfo>>> call, Throwable t) {
                t.printStackTrace();
                hideProgressDialog();
            }
        });
    }

    private void setMessageIsRead() {

        XqNetClient netClient =  new XqNetClient();
        JSONObject jsonobject = new JSONObject();

        String msgids = "";
        for(HistoryMessageInfo historyMessageInfo: historyMessageInfoList){
            if(historyMessageInfo.getData().getIsRead()  == 0){
                msgids = msgids +","+ historyMessageInfo.getMsgid();
            }
        }
        if(TextUtils.isEmpty(msgids)){
            return;
        }
        msgids = msgids.substring(1);
        try {
            jsonobject.put(Stringkey.Token, userInfo.getToken());
            jsonobject.put(Stringkey.UID, userInfo.getUid());
            jsonobject.put(Stringkey.Timestamp, TimeUtil.getSystemCurrentTimeLong()+"");
            jsonobject.put(Stringkey.msgId, msgids);
            jsonobject.put(Stringkey.Type, MessageType.device+"");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        showProgressDialog();
        Log.e("准备设置的数据："+jsonobject.toString(), "");
        netClient.setMessageIsRead(jsonobject.toString()).enqueue(new Callback<NetResult>(){//获取验证码
            @Override
            public void onResponse(Call<NetResult> call, Response<NetResult> response) {

                if(response.body().isSuccess()){
                    Log.e("已经设置状态为度过：", "");
                }else {
                    showToast(devicemessages.this, "设置已读失败");
                }
                hideProgressDialog();
            }

            @Override
            public void onFailure(Call<NetResult> call, Throwable t) {
                t.printStackTrace();
                hideProgressDialog();
            }
        });
    }

    private void initview() {


        title.setText("设备消息");
//        rightbutton.setVisibility(View.VISIBLE);
        rightbutton.setText("清除");



        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        deviceMessageAdapter = new DeviceMessageAdapter(historyMessageInfoList);
        recyclerView.setAdapter(deviceMessageAdapter);
        deviceMessageAdapter.notifyDataSetChanged();

        refreshLayout.setRefreshMode(QRefreshLayout.RefreshMode.FROM_BOTTOM);
        refreshLayout.setScrollUpChild(recyclerView);
        refreshLayout.setRefreshHandler(new RefreshHandler() {
            @Override
            public void onRefresh(QRefreshLayout refresh) {
            }

            @Override
            public void onLoadMore(QRefreshLayout refresh) {
                //准备刷新更火的数据
                getSystemHistory();
            }
        });
    }



    @OnClick(R.id.BACKER)
    public void onClick(View v) {
        finish();
    }

    public class DeviceMessagePush extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            HistoryMessageInfo historyMessageInfo = (HistoryMessageInfo) intent.getSerializableExtra(Stringkey.JpushKey);
            Log.e("DeviceMessage广播收到的设备信息："+ com.alibaba.fastjson.JSONObject.toJSONString(historyMessageInfo), "");
            //把改消息添加列表里面去
            historyMessageInfoList.clear();
            getSystemHistory();
        }
    }

    @OnClick(R.id.rightbutton)
    public void cleanMessage(){
        deleteMessages();
    }

    private void deleteMessages() {

        XqNetClient netClient =  new XqNetClient();
        JSONObject jsonobject = new JSONObject();

        String msgids = "";
        for(HistoryMessageInfo historyMessageInfo: historyMessageInfoList){

                msgids = msgids +","+ historyMessageInfo.getMsgid();

        }
        if(TextUtils.isEmpty(msgids)){
            return;
        }
        msgids = msgids.substring(1);
        try {
            jsonobject.put(Stringkey.Token, userInfo.getToken());
            jsonobject.put(Stringkey.UID, userInfo.getUid());
            jsonobject.put(Stringkey.Timestamp, TimeUtil.getSystemCurrentTimeLong()+"");
            jsonobject.put(Stringkey.msgId, msgids);
            jsonobject.put(Stringkey.Type, MessageType.device+"");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        showProgressDialog();
        Log.e("准备数据清除的数据："+jsonobject.toString(), "");
        netClient.deleteMessages(jsonobject.toString()).enqueue(new Callback<NetResult>(){//获取验证码
            @Override
            public void onResponse(Call<NetResult> call, Response<NetResult> response) {
                Log.e("数据清除："+ com.alibaba.fastjson.JSONObject.toJSONString(response.body()), "");
                if(response.body().isSuccess()){
                    Log.e("数据清除成功：", "");
                    getSystemHistory();
                }else {
                    showToast(devicemessages.this, "数据清除失败"+response.body().getMessage());
                }
                hideProgressDialog();
            }

            @Override
            public void onFailure(Call<NetResult> call, Throwable t) {
                t.printStackTrace();
                hideProgressDialog();
            }
        });
    }

}
